package com.mingqijia.gassafety.job.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.ConsumerServiceInfo;
import com.mingqijia.gassafety.db.entity.Contacts;
import com.mingqijia.gassafety.db.mapper.ConsumerServiceInfoMapper;
import com.mingqijia.gassafety.job.request.AccountNumberListRequest;
import com.mingqijia.gassafety.job.request.CompanyRequest;
import com.mingqijia.gassafety.job.request.ConsumerListRequest;
import com.mingqijia.gassafety.job.request.EquipmentListRequest;
import com.mingqijia.gassafety.job.request.HzRecordLogRequest;
import com.mingqijia.gassafety.job.request.LatestLogListRequest;
import com.mingqijia.gassafety.job.request.ManagerListRequest;
import com.mingqijia.gassafety.job.request.OrganizationalDepartmentListRequest;
import com.mingqijia.gassafety.job.request.RecordLogRequest;
import com.mingqijia.gassafety.job.request.WarningRecordInfoRequest;
import com.mingqijia.gassafety.job.request.bi.OneReportDetailRequest;
import com.mingqijia.gassafety.job.request.bi.OneReportRequest;
import com.mingqijia.gassafety.job.request.bi.DeviceReportRequest;
import com.mingqijia.gassafety.job.request.screen.ScreenCompanyManageReq;
import com.mingqijia.gassafety.job.response.AccountNumberResp;
import com.mingqijia.gassafety.job.response.AlertLogResponse;
import com.mingqijia.gassafety.job.response.BrokenLogResponse;
import com.mingqijia.gassafety.job.response.CompanyResponse;
import com.mingqijia.gassafety.job.response.ConsumerExport;
import com.mingqijia.gassafety.job.response.ConsumerResponse;
import com.mingqijia.gassafety.job.response.DateExporterResponse;
import com.mingqijia.gassafety.job.response.DtuListResponse;
import com.mingqijia.gassafety.job.response.EquipmentExport;
import com.mingqijia.gassafety.job.response.HangzhouAlertLogResponse;
import com.mingqijia.gassafety.job.response.LatestLogListResponse;
import com.mingqijia.gassafety.job.response.LatestLogResponse;
import com.mingqijia.gassafety.job.response.ManagerResponse;
import com.mingqijia.gassafety.job.response.OrganizationalDepartmentResp;
import com.mingqijia.gassafety.job.response.RecordDetailListResponse;
import com.mingqijia.gassafety.job.response.bi.OneReportDetailResponse;
import com.mingqijia.gassafety.job.response.bi.DeviceReportResponse;
import com.mingqijia.gassafety.job.response.bi.OneReportItemResponse;
import com.mingqijia.gassafety.job.response.screen.PlatformCompanyManageResp;
import com.mingqijia.gassafety.job.service.AccountNumberExportService;
import com.mingqijia.gassafety.job.service.AlertLogService;
import com.mingqijia.gassafety.job.service.CompanyService;
import com.mingqijia.gassafety.job.service.ConsumerService;
import com.mingqijia.gassafety.job.service.HistoryAlarmService;
import com.mingqijia.gassafety.job.service.HistoryBrokenService;
import com.mingqijia.gassafety.job.service.LatestLogService;
import com.mingqijia.gassafety.job.service.ManagerService;
import com.mingqijia.gassafety.job.service.OrganizationalDepartmentExportService;
import com.mingqijia.gassafety.job.service.RunningRecordService;
import com.mingqijia.gassafety.job.service.bi.DeviceReportStatService;
import com.mingqijia.gassafety.job.service.impl.ConsumerServiceInfoServiceImpl;
import com.mingqijia.gassafety.job.service.impl.ContactsServiceImpl;
import com.mingqijia.gassafety.job.service.impl.EquipmentServiceImpl;
import com.mingqijia.gassafety.job.service.screen.ScreenStatisticsService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.ConsumerServiceStatusEnum;
import com.mingqijia.gassafety.shared.request.VccAccountNumberListRequest;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 表格导出,内部接口
 *
 * @author wanghai
 * @since 2022-02-23
 */

@Slf4j
@RestController
@RequestMapping("/inner/v1/export")
public class FileExportController {
    @Autowired
    ConsumerService consumerService;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    LatestLogService latestLogService;
    @Autowired
    AlertLogService alertLogService;
    @Autowired
    HistoryBrokenService historyBrokenService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    ManagerService managerService;
    @Autowired
    CompanyService companyService;
    @Autowired
    RunningRecordService runningRecordService;

    @Autowired
    ContactsServiceImpl contactsService;
    @Autowired
    ConsumerServiceInfoServiceImpl consumerServiceInfoService;
    @Autowired
    ConsumerServiceInfoMapper consumerServiceInfoMapper;
    @Autowired
    ConfigureHolder holder;

    @Autowired
    OrganizationalDepartmentExportService organizationalDepartmentExportService;

    @Autowired
    AccountNumberExportService accountNumberExportService;

    @Autowired
    ScreenStatisticsService screenStatisticsService;

    @Autowired
    DeviceReportStatService deviceReportStatService;


    @PostMapping("/consumerList")
    @ApiOperation(value = "导出客户列表")
    public CommonResponse<DateExporterResponse<ConsumerExport>> consumerList(@RequestBody JSONObject jsonObject) {
        log.info("consumerList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        ConsumerListRequest request = JSONObject.parseObject(query.toString(), ConsumerListRequest.class);

        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //客户基本信息
        List<ConsumerResponse> consumerList = consumerService.consumerList(request).getList();

        List<Integer> consumerIds = consumerList.stream().map(ConsumerResponse::getId).collect(Collectors.toList());
        List<LatestLogListResponse> logList = null;
        if (CollectionUtil.isNotEmpty(consumerIds)) {
            //根据客户id得到所有dtuId, 查询设备的实时状态
            logList = latestLogService.getList(consumerIds, request);
        }

        //获取用户服务信息
        Map<String, ConsumerServiceInfo> consumerServiceInfoMap = new HashMap<>();
        if ("service".equals(request.getAuthority()) && CollectionUtils.isNotEmpty(consumerIds)) {
            log.info("服务信息consumerIds入参:{}", consumerIds);
            QueryWrapper<ConsumerServiceInfo> consumerServiceInfoWrapper = new QueryWrapper<>();
            consumerServiceInfoWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .in(ConsumerServiceInfo::getConsumerId, consumerIds);
            List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoMapper.selectList(consumerServiceInfoWrapper);
            if (CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
                consumerServiceInfoList.stream().forEach(item -> {
                    consumerServiceInfoMap.put(item.getImei(), item);
                });
                log.info("服务信息导出consumerServiceInfoMap:{}", consumerServiceInfoMap);
            }
        }

        //数据导出
        Long today = DateUtils.today().getTime();
        List<ConsumerExport> dataList = new ArrayList<ConsumerExport>();
        for (ConsumerResponse consumer : consumerList) {
            Boolean flag = true;
            for (LatestLogListResponse log : logList) {
                if (consumer.getId().equals(log.getConsumerId())) {
                    flag = false;
                    ConsumerExport response = new ConsumerExport();
                    BeanUtils.copyProperties(consumer, response);
                    BeanUtils.copyProperties(log, response);
                    //设备状态  0:离线 1:正常 2:低报 3:高报 4:故障 5:屏蔽
                    if (log.getEquipmentStatus() != null) {
                        String status = new String();
                        switch (log.getEquipmentStatus()) {
                            case 0:
                                status = "离线";
                                break;
                            case 1:
                                status = "正常";
                                break;
                            case 2:
                                status = "低报";
                                break;
                            case 3:
                                status = "高报";
                                break;
                            case 4:
                                status = "故障";
                                break;
                            case 5:
                                status = "屏蔽";
                                break;
                        }
                        response.setEquipmentStatus(status);
                    }
                    response.setCreatedAt(DateUtil.format(consumer.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"));
                    response.setLatestTime(DateUtil.format(log.getLatestTime(), "yyyy-MM-dd HH:mm:ss"));
                    response.setImeiBefore(org.apache.commons.lang.StringUtils.substringBefore(response.getImei(), "-"));
                    if (consumerServiceInfoMap.get(response.getImeiBefore()) != null && "service".equals(request.getAuthority())) {
                        response.setServiceInfo(consumerServiceInfoMap.get(response.getImeiBefore()).getServiceInfo());
                        response.setStartDate(DateUtils.dateFormat(consumerServiceInfoMap.get(response.getImeiBefore()).getStartDate()));
                        response.setEndDate(DateUtils.dateFormat(consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate()));
                        if (today == consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime() && request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode()) {
                            response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode());
                            dataList.add(response);
                        } else if (today < consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime()) {
                            if (consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime() - today <= 7 * 24 * 60 * 60 * 1000 && request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode()) {
                                response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode());
                                dataList.add(response);
                            } else if (consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime() - today <= 30 * 24 * 60 * 60 * 1000L && request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode()) {
                                response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode());
                                dataList.add(response);
                            } else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode()) {
                                response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode());
                                dataList.add(response);
                            }
                        } else if (today > consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime()) {
                            if (today - consumerServiceInfoMap.get(response.getImeiBefore()).getEndDate().getTime() <= 7 * 24 * 60 * 60 * 1000 && request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode()) {
                                response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode());
                                dataList.add(response);
                            } else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode()) {
                                response.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode());
                                dataList.add(response);
                            }
                        }
                        if (response.getServiceStatus() != null) {
                            response.setServiceStatusName(ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(response.getServiceStatus()).getName());
                        }
                    } else {
                        dataList.add(response);
                    }
                }
            }
            //该用户没有绑定设备时
            if (flag) {
                ConsumerExport response = new ConsumerExport();
                BeanUtils.copyProperties(consumer, response);
                if (consumer.getPositionLat() != null && consumer.getPositionLon() != null) {
                    response.setLocation(consumer.getPositionLat().toString() + "," + consumer.getPositionLon());
                }
                response.setCreatedAt(DateUtil.format(consumer.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"));
                dataList.add(response);
            }
        }
        log.info("dataList的大小 :{}", dataList.size());
        DateExporterResponse<ConsumerExport> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(dataList) || CollectionUtil.isNotEmpty(request.getConsumerIdList())) {
            exporterResponse.setCursor(null);
        } else {
            JSONObject json = new JSONObject();
            json.put("page", page.toString());
            json.put("pageSize", pageSize.toString());
            exporterResponse.setCursor(json);
        }

        Map<Integer, List<Contacts>> contacts = contactsService.getContacts(consumerIds, null);
        if (CollectionUtils.isNotEmpty(dataList)) {
            if (MapUtils.isNotEmpty(contacts)) {
                dataList.forEach(list -> {
                    list.setContact(latestLogService.dealContacts(contacts.get(list.getConsumerId())
                    ));
                });
            }
        }
        exporterResponse.setList(dataList);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/latestLogList")
    @ApiOperation(value = "导出实时监测列表")
    public CommonResponse<DateExporterResponse<LatestLogResponse>> latestLogList(@RequestBody JSONObject jsonObject) {
        log.info("latestLogList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        LatestLogListRequest request = JSONObject.parseObject(query.toString(), LatestLogListRequest.class);

        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //查询实时监测列表
        List<LatestLogResponse> exportList = latestLogService.list(request).getList();

        //数据导出
        DateExporterResponse<LatestLogResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", page.toString());
                json.put("pageSize", pageSize.toString());
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }


    /**
     * 设备excel导出
     *
     * @return
     */
    @PostMapping("export")
    @ApiOperation(value = "设备excel导出")
    public CommonResponse<DateExporterResponse<EquipmentExport>> equipmentList(@RequestBody JSONObject jsonObject) {
        log.info("equipmentList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        EquipmentListRequest request = JSONObject.parseObject(query.toString(), EquipmentListRequest.class);
        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        List<DtuListResponse> list = equipmentService.equipmentList(request).getList();
        log.info("equipmentList-list:{}", JSONObject.toJSONString(list));
        //数据导出
        List<EquipmentExport> dataList = new ArrayList<>();
        for (DtuListResponse dtu : list) {
            EquipmentExport equipmentExport = new EquipmentExport();
            BeanUtils.copyProperties(dtu, equipmentExport);
            equipmentExport.setActivateStatus(dtu.getActivateStatus() != null && dtu.getActivateStatus() == 0 ? "未激活" : "已激活");
            equipmentExport.setOpenStatus(dtu.getOpenStatus() != null && dtu.getOpenStatus() == 0 ? "未开通" : "已开通");
            equipmentExport.setRegisterStatus(dtu.getRegisterStatus() != null && dtu.getRegisterStatus() == 0 ? "未注册" : "已注册");
            equipmentExport.setValidity(dtu.getRegisterStatus() == null || (!StringUtils.isEmpty(dtu.getValidity()) && dtu.getValidity() == 0) ? "" : dtu.getValidity() + "");
            log.info("equipmentList-equipmentExport:{}", JSONObject.toJSONString(equipmentExport));
            dataList.add(equipmentExport);
        }
        DateExporterResponse<EquipmentExport> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(dataList)) {
            exporterResponse.setCursor(null);
        } else {
            JSONObject json = new JSONObject();
            json.put("page", page.toString());
            json.put("pageSize", pageSize.toString());
            exporterResponse.setCursor(json);
        }
        exporterResponse.setList(dataList);
        return CommonResponse.success(exporterResponse);
    }


    @PostMapping("/alertLogList")
    @ApiOperation(value = "导出报警记录列表")
    public CommonResponse<DateExporterResponse<AlertLogResponse>> alertLogList(@NotNull @RequestBody JSONObject jsonObject) {
        log.info("alertLogList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        RecordLogRequest request = JSONObject.parseObject(query.toString(), RecordLogRequest.class);

        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //客户基本信息
        List<AlertLogResponse> exportList = historyAlarmService.getAlarmList(request).getList();
        //数据导出
        DateExporterResponse<AlertLogResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", page.toString());
                json.put("pageSize", pageSize.toString());
                exporterResponse.setCursor(json);
            }
        }
        List<Integer> consumerIds = exportList.stream().map(AlertLogResponse::getConsumerId).collect(Collectors.toList());
        Set<Integer> cs = new HashSet<>(consumerIds);
        if (CollectionUtil.isNotEmpty(cs) && (cs.size() > 1 || (cs.size() == 1 && !cs.contains(null)))) {
            Map<Integer, List<Contacts>> contacts = contactsService.getContacts(consumerIds, null);
            if (MapUtils.isNotEmpty(contacts)) {
                exportList.forEach(list -> {
                    list.setContact(latestLogService.dealContacts(contacts.get(list.getConsumerId())
                    ));
                });
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/hangzhouAlertLogList")
    @ApiOperation(value = "导出报警记录列表")
    public CommonResponse<DateExporterResponse<HangzhouAlertLogResponse>> hangzhouAlertLogList(@NotNull @RequestBody JSONObject jsonObject) {
        log.info("hangzhouAlertLogList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        HzRecordLogRequest request = JSONObject.parseObject(query.toString(), HzRecordLogRequest.class);

        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        log.info("getHangZhouAlarmList入参:{}", request);
        //客户基本信息
        List<HangzhouAlertLogResponse> exportList = historyAlarmService.getHangZhouAlarmList(request).getList();
        //数据导出
        DateExporterResponse<HangzhouAlertLogResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", page.toString());
                json.put("pageSize", pageSize.toString());
                exporterResponse.setCursor(json);
            }
        }
        if (CollectionUtils.isNotEmpty(exportList)) {
            List<Integer> consumerIds = exportList.stream().map(HangzhouAlertLogResponse::getConsumerId).collect(Collectors.toList());
            Set<Integer> cs = new HashSet<>(consumerIds);
            if (CollectionUtil.isNotEmpty(cs) && (cs.size() > 1 || (cs.size() == 1 && !cs.contains(null)))) {
                Map<Integer, List<Contacts>> contacts = contactsService.getContacts(consumerIds, null);
                if (MapUtils.isNotEmpty(contacts)) {
                    exportList.forEach(list -> {
                        list.setContact(latestLogService.dealContacts(contacts.get(list.getConsumerId())
                        ));
                    });
                }
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/brokenLogList")
    @ApiOperation(value = "导出故障记录列表")
    public CommonResponse<DateExporterResponse<BrokenLogResponse>> brokenLogList(@RequestBody JSONObject jsonObject) {
        log.info("brokenLogList入参 :{}", jsonObject.toString());
        // 解析入参, 设置 service方法入参
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        HzRecordLogRequest request = JSONObject.parseObject(query.toString(), HzRecordLogRequest.class);

        Integer page = 1;
        Integer pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.valueOf(cursor.getString("page"));
            page++;
            pageSize = Integer.valueOf(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }

        //故障列表
        List<BrokenLogResponse> exportList = historyBrokenService.getList(request).getList();
        //数据导出
        DateExporterResponse<BrokenLogResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", page.toString());
                json.put("pageSize", pageSize.toString());
                exporterResponse.setCursor(json);
            }
        }
        List<Integer> consumerIds = exportList.stream().map(BrokenLogResponse::getConsumerId).collect(Collectors.toList());
        Set<Integer> cs = new HashSet<>(consumerIds);
        if (CollectionUtil.isNotEmpty(cs) && (cs.size() > 1 || (cs.size() == 1 && !cs.contains(null)))) {
            Map<Integer, List<Contacts>> contacts = contactsService.getContacts(consumerIds, null);
            if (MapUtils.isNotEmpty(contacts)) {
                exportList.forEach(list -> {
                    log.info("brokenLogList-list:{}", JSONObject.toJSONString(list));
                    list.setContact(latestLogService.dealContacts(contacts.get(list.getConsumerId())
                    ));
                });
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/userList")
    @ApiOperation(value = "导出账号列表")
    public CommonResponse<DateExporterResponse<ManagerResponse>> exportManagers(@RequestBody JSONObject jsonObject) {
        log.info("exportManagers入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        ManagerListRequest request = JSONObject.parseObject(query.toString(), ManagerListRequest.class);

        int page = 1;
        int pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //客户基本信息
        List<ManagerResponse> exportList = managerService.list(request).getList();
        //数据导出
        DateExporterResponse<ManagerResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", Integer.toString(page));
                json.put("pageSize", Integer.toString(pageSize));
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }


    @PostMapping("/companyList")
    @ApiOperation(value = "导出组织列表")
    public CommonResponse<DateExporterResponse<CompanyResponse>> exportCompanies(@RequestBody JSONObject jsonObject) {
        log.info("exportCompanies入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        CompanyRequest request = JSONObject.parseObject(query.toString(), CompanyRequest.class);

        int page = 1;
        int pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //客户基本信息
        List<CompanyResponse> exportList = companyService.list(request).getList();
        //数据导出
        DateExporterResponse<CompanyResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(exportList)) {
            exporterResponse.setCursor(null);
        } else {
            if (exportList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", Integer.toString(page));
                json.put("pageSize", Integer.toString(pageSize));
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(exportList);
        return CommonResponse.success(exporterResponse);
    }


    @PostMapping("/organizationalDepartment")
    @ApiOperation(value = "导出组织部门管理")
    public CommonResponse<DateExporterResponse<OrganizationalDepartmentResp>> exportOrganizationalDepartment(@RequestBody JSONObject jsonObject) {
        log.info("exportRunningRecord入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        OrganizationalDepartmentListRequest request = JSONObject.parseObject(query.toString(), OrganizationalDepartmentListRequest.class);

        int page = 1;
        int pageSize = 1000;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //企业信息
        List<OrganizationalDepartmentResp> manageRespPageUtil = organizationalDepartmentExportService.export(request);
        //数据导出
        DateExporterResponse<OrganizationalDepartmentResp> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        exporterResponse.setCursor(null);
        exporterResponse.setList(manageRespPageUtil);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/accountNumber")
    @ApiOperation(value = "导出账号管理")
    public CommonResponse<DateExporterResponse<AccountNumberResp>> exportAccountNumber(@RequestBody JSONObject jsonObject) {
        log.info("exportRunningRecord入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        VccAccountNumberListRequest request = JSONObject.parseObject(query.toString(), VccAccountNumberListRequest.class);

        int page = 1;
        int pageSize = 1000;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPageIndex(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPageIndex(page);
        }
        //企业信息
        List<AccountNumberResp> manageRespPageUtil = accountNumberExportService.export(request);
        //数据导出
        DateExporterResponse<AccountNumberResp> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(manageRespPageUtil)) {
            exporterResponse.setCursor(null);
        } else {
            if (manageRespPageUtil.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", Integer.toString(page));
                json.put("pageSize", Integer.toString(pageSize));
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(manageRespPageUtil);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/running/list")
    @ApiOperation(value = "导出账号列表")
    public CommonResponse<DateExporterResponse<RecordDetailListResponse>> exportRunningRecord(@RequestBody JSONObject jsonObject) {
        log.info("exportRunningRecord入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        WarningRecordInfoRequest request = JSONObject.parseObject(query.toString(), WarningRecordInfoRequest.class);

        int page = 1;
        int pageSize = 500;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //客户基本信息
        List<RecordDetailListResponse> detailList = runningRecordService.getDetailList(request);
        //数据导出
        DateExporterResponse<RecordDetailListResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(detailList)) {
            exporterResponse.setCursor(null);
        } else {
            if (detailList.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", Integer.toString(page));
                json.put("pageSize", Integer.toString(pageSize));
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(detailList);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/company/manage")
    @ApiOperation(value = "导出企业管理")
    public CommonResponse<DateExporterResponse<PlatformCompanyManageResp>> exportCompanyManage(@RequestBody JSONObject jsonObject) {
        log.info("exportRunningRecord入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        ScreenCompanyManageReq request = JSONObject.parseObject(query.toString(), ScreenCompanyManageReq.class);

        int page = 1;
        int pageSize = 1000;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }
        //企业信息
        List<PlatformCompanyManageResp> manageRespPageUtil = screenStatisticsService.companyManage(request);
        //数据导出
        DateExporterResponse<PlatformCompanyManageResp> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(manageRespPageUtil)) {
            exporterResponse.setCursor(null);
        } else {
            if (manageRespPageUtil.size() < pageSize) {
                exporterResponse.setCursor(null);
            } else {
                JSONObject json = new JSONObject();
                json.put("page", Integer.toString(page));
                json.put("pageSize", Integer.toString(pageSize));
                exporterResponse.setCursor(json);
            }
        }
        exporterResponse.setList(manageRespPageUtil);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/one/report/list")
    @ApiOperation(value = "导出一次情况统计报表")
    public CommonResponse<DateExporterResponse<OneReportItemResponse>> exportOneReportList(@RequestBody JSONObject jsonObject) {
        log.info("exportOneReportList入参 :{}", jsonObject.toString());
        JSONObject query = jsonObject.getJSONObject("query");
        OneReportRequest request = JSONObject.parseObject(query.toString(), OneReportRequest.class);

        //企业信息
        List<OneReportItemResponse> datas = deviceReportStatService.oneReportList(request);
        //数据导出
        DateExporterResponse<OneReportItemResponse> exporterResponse = new DateExporterResponse<>();
        exporterResponse.setList(datas);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/one/report/detail")
    @ApiOperation(value = "导出一次情况详细报表")
    public CommonResponse<DateExporterResponse<OneReportDetailResponse>> exportOneReportDetail(@RequestBody JSONObject jsonObject) {
        log.info("exportOneReportDetail入参 :{}", jsonObject.toString());
        JSONObject cursor = jsonObject.getJSONObject("cursor");
        JSONObject query = jsonObject.getJSONObject("query");
        OneReportDetailRequest request = JSONObject.parseObject(query.toString(), OneReportDetailRequest.class);

        int page = 1;
        int pageSize = 1000;
        if (cursor != null) {
            //当前 cursor中获得的数据是上次查询的游标
            page = Integer.parseInt(cursor.getString("page"));
            page++;
            pageSize = Integer.parseInt(cursor.getString("pageSize"));
            request.setPage(page);
            request.setPageSize(pageSize);

        } else {
            request.setPageSize(pageSize);
            request.setPage(page);
        }

        //企业信息
        PageUtil<OneReportDetailResponse> result = deviceReportStatService.oneReportDetail(request);
        List<OneReportDetailResponse> datas = new ArrayList<>();
        if (null!=result && !CollectionUtil.isEmpty(result.getList())) {
            datas = result.getList();
        }
        //数据导出
        DateExporterResponse<OneReportDetailResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(datas)) {
            exporterResponse.setCursor(null);
        } else if (result.getList().size() < pageSize) {
            exporterResponse.setCursor(null);
        } else {
            JSONObject json = new JSONObject();
            json.put("page", Integer.toString(page));
            json.put("pageSize", Integer.toString(pageSize));
            exporterResponse.setCursor(json);
        }
        exporterResponse.setList(datas);
        return CommonResponse.success(exporterResponse);
    }

    @PostMapping("/device/report/condition")
    @ApiOperation(value = "设备上报情况")
    public CommonResponse<DateExporterResponse<DeviceReportResponse>> deviceReportCondition(@RequestBody JSONObject jsonObject) {
        log.info("deviceReportCondition入参 :{}", jsonObject.toString());
        JSONObject query = jsonObject.getJSONObject("query");
        DeviceReportRequest request = JSONObject.parseObject(query.toString(), DeviceReportRequest.class);

        //企业信息
        List<DeviceReportResponse> deviceReportResponses = deviceReportStatService.deviceReport(request);
        //数据导出
        DateExporterResponse<DeviceReportResponse> exporterResponse = new DateExporterResponse<>();
        //如果查不到数据
        if (CollectionUtil.isEmpty(deviceReportResponses)) {
            exporterResponse.setCursor(null);
        }
        exporterResponse.setList(deviceReportResponses);
        return CommonResponse.success(exporterResponse);
    }

}
